import json
from django.shortcuts import render,redirect
from django.views import View
from django.http import HttpResponse, JsonResponse
from .models import Users
from itsdangerous import TimedJSONWebSignatureSerializer as Serialier
from itsdangerous import SignatureExpired
from django.contrib.auth import authenticate
from django.core.mail import send_mail
from django.shortcuts import get_object_or_404
from django.conf import settings
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import os
import re
from .crawler import getdata
from .models import Information
import csv

today=[]

#注册相关  类视图，清晰请求方式的区分 PUT DELET OPTION ....
class RegisterView(View):
    # 跳转到登陆画面
    def get(self,request):
        request.session['name'] = '1'
        return render(request, "myApp/user/register.html")

    #注册处理
    def post(self,request):
        username = request.POST.get("username");
        tel = request.POST.get("tel");
        email = request.POST.get("email");
        password = request.POST.get("password");
        password2 = request.POST.get("password2");
        msg = ""
        rep_dict = dict(tel=tel,username=username,email=email,password=password,password2=password2)
        if (not all([username,email,password,password2,tel])):
            msg="用户输入的信息不能为空"
            rep_dict["msg"] = msg
            return render(request, "myApp/user/register.html",rep_dict)

        #11位  13位  14位 （地域号 + 11位）18360939450 8618360939450  +8618360939450  （只是验证中国的手机号码）
        # if (not re.match(r'^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$',tel)):
        #    return render(request, "myApp/user/register.html",{"msg":"手机号码格式不正确"})

        if (not re.match(r'^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$',email)):
            msg = "邮箱输入错误"
            rep_dict["msg"] = msg
            return render(request, "myApp/user/register.html", rep_dict)

        if (password != password2):
            msg = "两次密码不一致"
            rep_dict["msg"] = msg
            rep_dict.pop("password")
            rep_dict.pop("password2")
            return render(request, "myApp/user/register.html", rep_dict)
        # 先要去检查电话是否存在
        #user = Users.objects.get(email=email,user_phone = tel)
        user =  authenticate(email=email,user_phone = tel)
        if user is not None:
            msg = "手机号码或者email已经存在，请重新注册。"
            rep_dict["msg"] = msg
            rep_dict.pop("password")
            rep_dict.pop("password2")
            return render(request, "myApp/user/register.html", rep_dict)
        #一定要是使用他自己的这种方式区创建而不是使用Users()去创建--你自己的项目和Django框架的整合
        print("111"+password)
        user = Users.objects.create_user(username,email,password)
        user.user_phone = tel

        #注册完之后该用户是不能登陆的，只有后段承认之后才可以使用，此处为了方便项目的进行，手动改成1
        user.is_active = 1

        #更新方法
        user.save()

        #发送激活邮件，包含一个激活的链接在（get请求）
        serializer = Serialier(settings.SECRET_KEY, 3600)
        info = {"user_id": user.id}
        serialier_id_token = serializer.dumps(info)
        serialier_id_token = serialier_id_token.decode()

        # 定义的发送邮件的方法；异步
        try:
            #测试方法
            #raise Exception("测试")
            send_register_active_email(user.email,user.username,serialier_id_token)
        except Exception as e:
            #print(e)
            #return render(request, "myApp/common/error.html", {"msg": "邮件发送失败，请检查相应配置或者联系管理员","jump_index":"http://127.0.0.1:8000/index/"})
            request.session['name'] = username
            return render(request, "myApp/index/index.html", {"userName": username})
        request.session['name'] = username
        return render(request, "myApp/index/index.html", {"userName": username})

# 激活用户视图
class ActiveView(View):
    def get(self,request,token):
        serializer = Serialier(settings.SECRET_KEY, 3600)
        try:
            user_dic = serializer.loads(token)
            id = user_dic["user_id"]
            user = Users.objects.get(id=id)
            user.is_active = 1
            user.save()
            return redirect(reversed('login'))
        except SignatureExpired as se:
            return HttpResponse("激活信息已经过期")
    def post(self, request, token):
        print("c")
        pass

#登陆
class Login(View):


    # def post(self,request):
    #     print("aaa")
    #     # 1 画面输入项目的检查
    #     tel = request.POST.get("tel")
    #     email = request.POST.get("email")
    #     password = request.POST.get("password")
    #     password2 = request.POST.get("password2")
    #     cb1 = request.POST.get("cb1")
    #
    #     # username = request.POST.get("username")
    #
    #     # 1.1 输入项目不能为空
    #     rep_dict = dict(tel=tel, email=email, password=password, password2=password2)
    #
    #     if not all([password, password2]):
    #         msg = "密码不能为空"
    #         rep_dict["msg"] = msg
    #         return render(request, "myApp/user/login.html", rep_dict)
    #
    #     if not all([tel]) and not all([email]):
    #         msg = "电话号码或者邮箱必修输入"
    #         rep_dict["msg"] = msg
    #         return render(request, "myApp/user/login.html", rep_dict)
    #
    #     if password != password2:
    #         msg = "两次密码不一致"
    #         rep_dict["msg"] = msg
    #         rep_dict.pop("password")
    #         rep_dict.pop("password2")
    #         return render(request, "myApp/user/login.html", rep_dict)
    #
    #     if all([tel,email]):
    #         rep_dict[email] = ""
    #         rep_dict[tel] = ""
    #         return render(request, "myApp/common/error.html",{"msg": "系统出故障，请联系管理员", "jump_index": "http://127.0.0.1:8000/index/"})
    #     user_by_auth = 1
    #     if (tel == ""):
    #         tel = None
    #     if (email == ""):
    #         email = None
    #
    #     if (tel is not None  )and (email is None) :
    #         # 2.2 手机号登陆
    #         try:
    #             user_by_auth = Users.objects.get(email=email)
    #             rep_dict[email] = ""
    #         except Users.DoesNotExist:
    #             user_by_auth = None
    #     elif (tel is None) and (email is not None):
    #         # 先判断等方式
    #         # 1.2  输入项目必须合法 ,排除一些关键字，不如说 script ,比如说# ,比如说 delete ********
    #
    #         # 2 根据db存放数据进行比较
    #         # 2.1 验证邮箱
    #
    #         try:
    #             user_by_auth =  Users.objects.get(email=email)
    #             rep_dict[tel ]= ""
    #         except Users.DoesNotExist:
    #             user_by_auth = None
    #
    #     if user_by_auth is None:
    #         msg = "用户不存在，请注册!"
    #         rep_dict["msg"] = msg
    #         return render(request, "myApp/user/login.html", rep_dict)
    #
    #     # TODO
    #     auth_password = user_by_auth.password
    #
    #     if user_by_auth.password != auth_password:
    #         msg = "密码输入有误"
    #         rep_dict["msg"] = msg
    #         rep_dict.pop("password")
    #         rep_dict.pop("password2")
    #         return render(request, "myApp/user/login.html", rep_dict)
    #     if cb1 is not None:
    #         # 有设置redis  TODO
    #         pass
    #     # 设置session
    #     request.session["user_id"] = user_by_auth.id
    #     # 3 处理结束跳转画面
    #     return render(request, "myApp/index/index.html", {"userName": user_by_auth.username})
#修改
    def post(self, request):
        try:
            cookie_user = request.COOKIES.get('cookie_user')
        except:
            cookie_user = ''
        if cookie_user:
            username,password = cookie_user.split('-')
            cb1 = None
        else:
            # 1 画面输入项目的检查
            # tel = request.POST.get("tel")
            # email = request.POST.get("email")
            password = request.POST.get("password")
            # password2 = request.POST.get("password2")
            cb1 = request.POST.get("cb1")
            username = request.POST.get("username")

        # 1.1 输入项目不能为空
        # rep_dict = dict(tel=tel, email=email, password=password, password2=password2)

        rep_dict={}
        if password=='null':
            msg = "密码不能为空"
            rep_dict["msg"] = msg
            return render(request, "myApp/user/login.html", rep_dict)

        if username=='null':
            msg = "用户名必修输入"
            rep_dict["msg"] = msg
            return render(request, "myApp/user/login.html", rep_dict)

        if '@' not in username:
            # 2.2 手机号登陆
            try:
                # user_by_auth = authenticate(user_phone=username,password=password)
                # print(user_by_auth)
                user_by_auth = Users.objects.get(user_phone=username)
                # rep_dict[email] = ""
            except Users.DoesNotExist:
                user_by_auth = None
        else:
            # 先判断等方式
            # 1.2  输入项目必须合法 ,排除一些关键字，不如说 script ,比如说# ,比如说 delete ********

            # 2 根据db存放数据进行比较
            # 2.1 验证邮箱

            try:
                # user_by_auth = authenticate(email=username)
                user_by_auth = Users.objects.get(email=username)
                # rep_dict[tel] = ""
            except Users.DoesNotExist:
                user_by_auth = None

        if user_by_auth is None:
            msg = "用户不存在，请注册!"
            rep_dict["msg"] = msg
            return render(request, "myApp/user/login.html", rep_dict)

        # TODO

        auth_password = user_by_auth.password
        if user_by_auth.check_password(password):
            if cb1 is not None:
                # 有设置redis  TODO
                response = HttpResponse('登陆成功')
                cookie_user = username + '-' + password

                response.set_cookie('cookie_user', cookie_user,
                                    expires=datetime.datetime.now() + datetime.timedelta(days=90))
            # 设置session
            request.session["user_id"] = user_by_auth.id
            # 3 处理结束跳转画面
            request.session['name'] = username
            return render(request, "myApp/index/index.html", {"userName": user_by_auth.username})
        else:
            msg = "密码输入有误"
            rep_dict["msg"] = msg
            return render(request, "myApp/user/login.html", rep_dict)



    def get(self,request):
        # user / login
        return render(request, "myApp/user/login.html")
        # self.post(self)


#跳转到登陆画面
def toLogin(request):
    return render(request,"myApp/user/login.html")
#登陆
def dologin(request):
    try:
        request.session.get('name')
    except:
        request.session['name'] = '1'
    return render(request, "myApp/user/index.html")

#跳转到注册画面
def toRegisters(request):
    return render(request,"myApp/user/register.html")

def index(request):
    try:
        request.session.get('name')
    except:
        request.session['name'] = '1'
    return render(request,"myApp/index/index.html")


def upfile(request):
    return render(request,'myApp/common/upfile.html')

from django.conf import settings
def savefile(request):
    if request.method=="POST":
        f=request.FILES["file"]
        # 文件在服务器端的路径
        filePath=os.path.join(settings.MDEIA_ROOT,f.name)
        # 文件上传就相当于文件复制
        with open(filePath,'wb') as fp:
            # chunks（），防止文件过大占用内存，将其转化为一个生成器。
            for info in f.chunks():
                fp.write(info)
        return HttpResponse("上传成功")
    else:
        return HttpResponse("上传失败")

# 暂时作为临时方法，以后用于celert
def send_register_active_email(to_main_user_mail, username, token):

    # 链接包含用户id  http://127.0.0.1:8080/user/active/{userId}?唯一id

    msg11 = "<h1>%s疾病预警系统欢迎您注册用户，点击下面链接进行激活：<h1><a hrefd='http://127.0.0.1:8080/user/active/%s'>http://127.0.0.1:8080/user/active/%s</a>" % (username, token, token)
    # recipt_list = [user.email]

    # 测试不能通过，不知道什么原因
    # send_mail(subject, "", context, recipt_list,html_message=msg11)
    # coding:utf-8
    # 第三方 SMTP 服务
    mail_host = settings.EMAIL_HOST  # 设置服务器
    mail_user = settings.EMAIL_FROM  # 用户名
    mail_pass = settings.EMAIL_HOST_PASSWORD  # "dkhafgqsflsjbhhg" 口令,QQ邮箱是输入授权码，在qq邮箱设置 里用验证过的手机发送短信获得，不含空格

    sender = settings.EMAIL_FROM
    receivers = [to_main_user_mail]  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱

    # 设置格式
    message = MIMEText(msg11, 'html', 'utf-8')
    message['From'] = "疾病预警系统<http://127.0.0.1:8000/user/index>"
    message['To'] = to_main_user_mail

    subject = '疾病预警系统欢迎您:用户激活'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, settings.EMAIL_PORT)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        smtpObj.quit()
        print(u"邮件发送成功")
    except smtplib.SMTPException as e:
        print(e)
        pass

    """发送激活邮件


    # 组织邮件信息
    subject = '天天生鲜欢迎信息'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [to_main_user_mail]
    html_message = '<h1>%s, 欢迎你成为天天生鲜注册会员</h1>请点击下面连接激活你的账户<br/><a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>' % (username, token, token)
    send_mail(subject, message, sender, receiver, html_message=html_message)
    """

def forecast(request):
    print("a")
    return render(request, "myApp/forecast/forecast.html")

def inform(request):
    return render(request, "myApp/inform/inform.html")

def error(request):
    return render(request,"myApp/common/error.html")



def incidence(request):
    return render(request, 'myApp/visualization/incidence.html')

def mysystem(request):
    return render(request, 'myApp/forecast/mysystem.html')


def rawdata(request):
    return render(request,'myApp/rawdata/rawdata.html')

def line(request):
    return render(request,'myApp/visualization/line.html')

def tuberline(request):
    return render(request,'myApp/visualization/tuberline.html')

def aboutus(request):
    return render(request,'myApp/aboutus/aboutus.html')

def visual(request):
    return render(request,'myApp/visualization/visual.html')

def citymap(request):
     return render(request,'myApp/visualization/tuberhuaianmap.html')

def tuberhuaianmap(request):
    return render(request,'myApp/visualization/tuberhuaianmap.html')
def fluline(request):
    return render(request,'myApp/visualization/fluline.html')
def crawler(request):
    return render(request,'myApp/index/crawler.html')

# 测试
def test_api(request):
    return JsonResponse({"result": 0, "msg": "执行成功"})

def get_data(request):
    listdata=getdata.get_pm25_and_weather("huaian")
    print(111)
    print(listdata)
    print(111)
    a = '        '.join(listdata)
    return HttpResponse("AQI指数，PM2.5，PM10，"
                        "CO，NO2，SO2，O3，天气状况，"
                        "风向风速，实时温度，"
                        "相对湿度:\n"+str(a))

def get_tianqidata(request):
    listdata=getdata.get_pm25_and_weather("huaian")
    l1 = ["AQI指数","PM2.5","PM10","CO","NO2","SO2","O3","天气状况","风向风速","实时温度","相对湿度"]
    re = []
    re.append(l1)
    re.append(listdata)
    # a = '        '.join(listdata)
    return HttpResponse(json.dumps(re,cls=DateEncoder,ensure_ascii=False))



def get_line_data(request):
    if request.method == "POST":
            # name = request.POST.get('name')
            listdata = getdata.get_pm25_and_weather("huaian")
            print(listdata)
            return HttpResponse(json.dumps(listdata))

###################################line.html#########################################
#     肺结核
def get_line_fdata(request):
    if request.method == "POST":
            # name = request.POST.get('name')
            listdata = [2692,2513,2609,2576,2310,2226,2034,1993,1798,1830]
            print(listdata)
            return HttpResponse(json.dumps(listdata))
#     流感
def get_line_ldata(request):
    if request.method == "POST":
            # name = request.POST.get('name')
            listdata = [1216,1786,1262,1485,2198,2184,2084,2081,2084,1320]
            print(listdata)
            return HttpResponse(json.dumps(listdata))
#    HIV
def get_line_hdata(request):
    if request.method == "POST":
            # name = request.POST.get('name')
            listdata = [39,55,57,86,79,113,127,152,142,141]
            print(listdata)
            return HttpResponse(json.dumps(listdata))

###################################line.html#########################################

###################################flueline.html#########################################
#     妇幼保健所
def get_line_mdata(request):
    if request.method == "POST":
            # name = request.POST.get('name')
            listdata = [567, 846, 607, 616, 993, 1054, 1042, 1041, 1040, 660, 1040]
            print(listdata)
            return HttpResponse(json.dumps(listdata))
#     第二人民医院
def get_line_sdata(request):
    if request.method == "POST":
            # name = request.POST.get('name')
            listdata = [649,922,655,869,1205,1130,1042,1140,1044,1040,660]
            print(listdata)
            return HttpResponse(json.dumps(listdata))

###################################flueline.html#########################################

###################################tuberline.html#########################################
#     洪泽
def get_line_hzdata(request):
    if request.method == "POST":
            # name = request.POST.get('name')
            listdata = [224,206,156,198,186,125,72,103,92,100,108]
            print(listdata)
            return HttpResponse(json.dumps(listdata))

#     涟水
def get_line_lsdata(request):
    if request.method == "POST":
            # name = request.POST.get('name')
            listdata = [625,671,683,562,564,518,478,375,431,331,305]
            print(listdata)
            return HttpResponse(json.dumps(listdata))


#     淮安区
def get_line_hadata(request):
    if request.method == "POST":
        # name = request.POST.get('name')
        listdata = [774,580,594,629,631,487,594,546,568,531,575]
        print(listdata)
        return HttpResponse(json.dumps(listdata))


#     淮阴区
def get_line_hydata(request):
    if request.method == "POST":
        # name = request.POST.get('name')
        listdata = [480,406,346,474,471,441,328,324,304,276,246]
        print(listdata)
        return HttpResponse(json.dumps(listdata))

#     清江浦区
def get_line_qjpdata(request):
    if request.method == "POST":
            # name = request.POST.get('name')
            listdata = [211,194,139,133,118,248,206,182,191,188,171]
            print(listdata)
            return HttpResponse(json.dumps(listdata))


#     盱眙
def get_line_xydata(request):
    if request.method == "POST":
        # name = request.POST.get('name')
        listdata = [506,414,405,422,417,308,390,367,268,263,318]
        print(listdata)
        return HttpResponse(json.dumps(listdata))


#     金湖
def get_line_jhdata(request):
    if request.method == "POST":
        # name = request.POST.get('name')
        listdata = [209,221,190,191,189,183,168,137,139,109,106]
        print(listdata)
        return HttpResponse(json.dumps(listdata))
###################################tuberline.html#########################################
import datetime
class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d')

        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")

        else:
            return json.JSONEncoder.default(self, obj)

###################################咨讯#########################################
# 获取咨讯
def get_informations(request):
#.value_list('title','content')
    informations_list = Information.objects.values_list('isShow','title','content','lastTime')
    info = []
    for i in informations_list:
        if i[0]:
            info.append(list(i))
    print(info)
    return HttpResponse(json.dumps(info,cls=DateEncoder,ensure_ascii=False),content_type='application/json; charset=utf-8')

def get_wxinformations(request):
#.value_list('title','content')
    informations_list = Information.objects.values_list('id','isShow','title','content','lastTime')
    info = []
    info_wx = {}
    for i in informations_list:
        if i[0]:
            info.append(list(i))
    print(info)
    return HttpResponse(json.dumps(info,cls=DateEncoder,ensure_ascii=False),content_type='application/json; charset=utf-8')


def get_info_sum(request):
#.value_list('title','content')
    informations_list = Information.objects.values_list('isShow','title','content')
    info = []
    for i in informations_list:
        if i[0]:
            info.append(list(i))
    S = len(info)
    return HttpResponse(str(S))
###################################咨讯#########################################


###################################发病情况#########################################
def get_FHTday_data(request):
    # print(os.getcwd())  # 获得当前工作目录
    # return HttpResponse("1")
    f = open("./templates/myApp/data/FLUByDay.csv", 'r')
    # f = open("{ % templates 'myApp/data/FLUByDay.csv' %}", 'r')
    FLUByDay = csv.reader(f)
    FLUByDaylist = list(FLUByDay)
    FLUByDaylist.pop(0)
    f.close()

    f = open("./templates/myApp/data/HIVByDay.csv", 'r')
    # print(FLUByDaylist)
    HIVByDay = csv.reader(f)
    HIVByDay = list(HIVByDay)
    HIVByDay.pop(0)
    f.close()

    f = open("./templates/myApp/data/TUBByDay.csv", 'r')
    # print(FLUByDaylist)
    TUBByDay = csv.reader(f)
    TUBByDay = list(TUBByDay)
    TUBByDay.pop(0)
    f.close()

    l=[]
    riqi=[]
    shuju1=[]
    shuju2=[]
    shuju3=[]
    for i in FLUByDaylist:
        for j in HIVByDay:
            if i[0]==j[0]:
                for z in TUBByDay:
                    if j[0]==z[0]:
                        riqi.append(i[0])
                        shuju1.append(i[1])
                        shuju2.append(j[1])
                        shuju3.append(z[1])
                        break

    l.append(riqi)
    l.append(shuju1)
    l.append(shuju2)
    l.append(shuju3)

    return HttpResponse(json.dumps(l, cls=DateEncoder, ensure_ascii=False),
                        content_type='application/json; charset=utf-8')

def get_FHTmon_data(request):
    # print(os.getcwd())  # 获得当前工作目录
    # return HttpResponse("1")
    f = open("./templates/myApp/data/FLUByMonth.csv", 'r',encoding='gbk')
    # f = open("{ % templates 'myApp/data/FLUByDay.csv' %}", 'r')
    FLUByDay = csv.reader(f)
    FLUByDaylist = list(FLUByDay)
    FLUByDaylist.pop(0)
    f.close()

    f = open("./templates/myApp/data/HIVByMonth.csv", 'r',encoding='gbk')
    # print(FLUByDaylist)
    HIVByDay = csv.reader(f)
    HIVByDay = list(HIVByDay)
    HIVByDay.pop(0)
    f.close()

    f = open("./templates/myApp/data/TUBByMonth.csv", 'r',encoding='gbk')
    # print(FLUByDaylist)
    TUBByDay = csv.reader(f)
    TUBByDay = list(TUBByDay)
    TUBByDay.pop(0)
    f.close()

    l=[]
    riqi=[]
    shuju1=[]
    shuju2=[]
    shuju3=[]
    for i in FLUByDaylist:
        for j in HIVByDay:
            if i[0]==j[0]:
                for z in TUBByDay:
                    if j[0]==z[0]:
                        riqi.append(i[0])
                        shuju1.append(i[1])
                        shuju2.append(j[1])
                        shuju3.append(z[1])
                        break

    l.append(riqi)
    l.append(shuju1)
    l.append(shuju2)
    l.append(shuju3)

    return HttpResponse(json.dumps(l, cls=DateEncoder, ensure_ascii=False),
                        content_type='application/json; charset=utf-8')

def get_FHTyear_data(request):
    # print(os.getcwd())  # 获得当前工作目录
    # return HttpResponse("1")
    f = open("./templates/myApp/data/FLUByYear.csv", 'r',encoding='utf-8')
    # f = open("{ % templates 'myApp/data/FLUByDay.csv' %}", 'r')
    FLUByDay = csv.reader(f)
    FLUByDaylist = list(FLUByDay)
    FLUByDaylist.pop(0)
    f.close()

    f = open("./templates/myApp/data/HIVByYear.csv", 'r',encoding='utf-8')
    # print(FLUByDaylist)
    HIVByDay = csv.reader(f)
    HIVByDay = list(HIVByDay)
    HIVByDay.pop(0)
    f.close()

    f = open("./templates/myApp/data/TUBByYear.csv", 'r',encoding='utf-8')
    # print(FLUByDaylist)
    TUBByDay = csv.reader(f)
    TUBByDay = list(TUBByDay)
    TUBByDay.pop(0)
    f.close()

    l=[]
    riqi=[]
    shuju1=[]
    shuju2=[]
    shuju3=[]
    for i in FLUByDaylist:
        for j in HIVByDay:
            if i[0]==j[0]:
                for z in TUBByDay:
                    if j[0]==z[0]:
                        riqi.append(i[0])
                        shuju1.append(i[1])
                        shuju2.append(j[1])
                        shuju3.append(z[1])
                        break

    l.append(riqi)
    l.append(shuju1)
    l.append(shuju2)
    l.append(shuju3)

    return HttpResponse(json.dumps(l, cls=DateEncoder, ensure_ascii=False),
                        content_type='application/json; charset=utf-8')
###################################发病情况#########################################

from .forecast import sk3,sendknn
def get_knnpre_data(request):
    l = getdata.get_pm25_and_weather("huaian")
    l = l[0:7]
    t = l[5]
    l[5] = l[4]
    l[4] = l[3]
    l[3] = t
    # for i in range(len(l)):
    #     l[i] = int(float(l[i]))
    resu = sk3.getknndata(l)
    # resu = skpre.get_preknn(l)
    print(resu)
    # sendknn.sendknn(resu)
    return HttpResponse(str(resu))

from .forecast import pca,sendpca

def get_pcapre_data(request):
    l = getdata.get_pm25_and_weather("huaian")
    l = l[0:7]
    t = l[5]
    l[5] = l[4]
    l[4] = l[3]
    l[3] = t
    resu = pca.getpcadata(l)
    print(resu)
    # sendpca.sendpca(resu)
    return HttpResponse(str(resu))

from .models import Users

#发送邮件
def send_knn_data(request):
    can_email = Users.objects.all().values_list('isMail','email')
    lis = []
    for em in can_email:
        if em[0]:
            lis.append(em[1])

    print(lis)
    l = getdata.get_pm25_and_weather("huaian")
    l = l[0:7]
    t = l[5]
    l[5] = l[4]
    l[4] = l[3]
    l[3] = t
    resu = sk3.getknndata(l)
    print(resu)
    sendknn.sendknn(resu,lis)
    return HttpResponse(str(resu))
#发送邮件
def send_pca_data(request):
    can_email = Users.objects.all().values_list('isMail','email')
    lis = []
    for em in can_email:
        if em[0]:

            lis.append(em[1])

    print(lis)
    l = getdata.get_pm25_and_weather("huaian")
    l = l[0:7]
    t = l[5]
    l[5] = l[4]
    l[4] = l[3]
    l[3] = t
    resu = pca.getpcadata(l)
    print(resu)
    sendpca.sendpca(resu,lis)
    return HttpResponse(str(resu))

def zhuxiao(request):
    try:
        cookie_user = request.COOKIES.get('cookie_user')
        response = HttpResponse('登陆成功')
        response.delete_cookie('cookie_user')
    except:
        pass
    request.session.flush()
    return render(request, "myApp/user/login.html")


def wxlogin(request):
    json_dic = eval(request.body)
    username = str(json_dic['name'])
    password = str(json_dic['pwd'])
    print(username)
    print(password)
    # 1.1 输入项目不能为空
    # rep_dict = dict(tel=tel, email=email, password=password, password2=password2)

    rep_dict = {}
    msg = '登录成功'
    if password == '':
        msg = "密码不能为空"
        return HttpResponse(str(msg))

    if username == '':
        msg = "用户名必修输入"
        return HttpResponse(str(msg))

    if '@' not in username:
        # 2.2 手机号登陆
        try:
            user_by_auth = Users.objects.get(user_phone=username)
            # rep_dict[email] = ""
        except Users.DoesNotExist:
            user_by_auth = None
    else:
        # 先判断等方式
        # 1.2  输入项目必须合法 ,排除一些关键字，不如说 script ,比如说# ,比如说 delete ********

        # 2 根据db存放数据进行比较
        # 2.1 验证邮箱

        try:
            user_by_auth = Users.objects.get(email=username)
            # rep_dict[tel] = ""
        except Users.DoesNotExist:
            user_by_auth = None

    if user_by_auth is None:
        msg = "用户不存在，请注册!"
        return HttpResponse(str(msg))

    # TODO
    auth_password = user_by_auth.password
    if user_by_auth.check_password(password):
        # msg = "密码输入有误"
        return HttpResponse(str(msg))
    else:
        msg = "密码输入有误"
        return HttpResponse(str(msg))


##获取rnn,cnn预测
from .forecast import pre_rnn_cnn
def get_rnn_data(request):
    global today
    if len(today)==0:
        l = getdata.get_pm25_and_weather("huaian")
        today.append(datetime.datetime.now())
        today.append(l)
    elif today[0]!=datetime.datetime.now():
        l = getdata.get_pm25_and_weather("huaian")
        today.append(datetime.datetime.now())
        today.append(l)
    else:
        l = today[1]
        print("获取全局变量的值")
    l = l[0:7]
    for i in range(len(l)):
        l[i] = int(float(l[i]))
    t = l[5]
    l[5] = l[4]
    l[4] = l[3]
    l[3] = t
    resu = pre_rnn_cnn.get_rnndata(l)
    print(resu)
    return HttpResponse(str(resu))
def get_cnn_data(request):
    l = getdata.get_pm25_and_weather("huaian")
    l = l[0:7]
    for i in range(len(l)):
        l[i] = int(float(l[i]))
    t = l[5]
    l[5] = l[4]
    l[4] = l[3]
    l[3] = t
    resu = pre_rnn_cnn.get_cnndata(l)
    print(resu)
    # return HttpResponse("1111")
    return HttpResponse(str(resu))









